package com.totoro.tyrank.manager;

import com.totoro.tyrank.data.ConfigData;
import com.totoro.tyrank.data.MySQLData;
import com.zaxxer.hikari.HikariConfig;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;

import java.io.File;
import java.util.Map;

public class DatasourceManager {
    private final YamlConfiguration config;
    private final Plugin plugin;

    // 从插件数据目录加载配置
    public DatasourceManager(Plugin plugin) {
        this.plugin = plugin;
        File configFile = new File(plugin.getDataFolder().getPath(), "datasource.yml");
        if (!configFile.exists()) {
            plugin.saveResource("datasource.yml", false);
        }
        this.config = YamlConfiguration.loadConfiguration(configFile);
    }

    // 将配置转换为HikariConfig对象（需传入外部获取的数据库连接信息）
    public HikariConfig toHikariConfig(MySQLData mySQLData) {
        HikariConfig hikariConfig = new HikariConfig();

        String jdbcUrl = String.format("jdbc:mysql://%s:%s/%s?useSSL=false&serverTimezone=UTC",
                mySQLData.getIp(), mySQLData.getPort(), mySQLData.getDatabaseName());
        hikariConfig.setJdbcUrl(jdbcUrl);
        hikariConfig.setUsername(mySQLData.getUserName());
        hikariConfig.setPassword(mySQLData.getPassword());

        // 2. HikariCP核心配置（读取DefaultSettings）
        String driverClassName = config.getString("DefaultSettings.DriverClassName");
        if (driverClassName != null && !driverClassName.isEmpty()) {
            hikariConfig.setDriverClassName(driverClassName);
        }

        hikariConfig.setAutoCommit(config.getBoolean("DefaultSettings.AutoCommit"));
        hikariConfig.setMinimumIdle(config.getInt("DefaultSettings.MinimumIdle"));
        hikariConfig.setMaximumPoolSize(config.getInt("DefaultSettings.MaximumPoolSize"));
        hikariConfig.setValidationTimeout(config.getLong("DefaultSettings.ValidationTimeout"));
        hikariConfig.setConnectionTimeout(config.getLong("DefaultSettings.ConnectionTimeout"));
        hikariConfig.setIdleTimeout(config.getLong("DefaultSettings.IdleTimeout"));
        hikariConfig.setMaxLifetime(config.getLong("DefaultSettings.MaxLifetime"));

        // 3. 连接测试查询（仅当非空时设置，~表示不设置）
        String testQuery = config.getString("DefaultSettings.ConnectionTestQuery");
        if (testQuery != null && !testQuery.equals("~")) {
            hikariConfig.setConnectionTestQuery(testQuery);
        }

        // 4. MySQL驱动优化参数（DataSourceProperty）
        Map<String, Object> dataSourceProps = config.getConfigurationSection("DefaultSettings.DataSourceProperty").getValues(false);
        for (Map.Entry<String, Object> entry : dataSourceProps.entrySet()) {
            Object value = entry.getValue();
            if (value != null && !value.toString().equals("~")) {
                hikariConfig.addDataSourceProperty(entry.getKey(), value);
            }
        }

        return hikariConfig;
    }
}
